package com.tpyule.tpclass.web.Controller;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.tpyule.tpclass.entity.bean.ResultBean;
import com.tpyule.tpclass.entity.bean.SuccessResultBean;
import com.tpyule.tpclass.util.FileUpload.BaseUpload;
import net.sf.json.JSONObject;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author zzz
 * @version 1.0
 * @date 2020/3/27 12:16
 */
@RestController
@RequestMapping("/upload")
public class UploadController extends BaseController {
    @RequestMapping("/getSignature")
    @ResponseBody
    public void getSignature(HttpServletRequest request, HttpServletResponse response){
        String accessId = "LTAI4Fbz6rZcSTb7aHxv38cW"; // 请填写您的AccessKeyId。
        String accessKey = "WrdEj5QuXRAHvOF5iQ1muXLxhZ2HQe"; // 请填写您的AccessKeySecret。
        String endpoint = "cdn.404zz.cn"; // 请填写您的 endpoint。
        String bucket = "jidiwangluo"; // 请填写您的 bucketname 。
        String host = "http://"+ endpoint ; // host的格式为 bucketname.endpoint
        // callbackUrl为 上传回调服务器的URL，请将下面的IP和Port配置为您自己的真实信息。
        //String callbackUrl = "http://88.88.88.88:8888";
        String type = request.getParameter("type");
        // 用户上传文件时指定的前缀。
        String dir = "other";
        if("image".equals(type)){
            dir = "course/image";
        }else if ("video".equals(type)){
            dir = "course/video";
        }else if ("file".equals(type)){
            dir = "course/file";
        }else if ("prtImage".equals(type)){
            dir = "learn/image";
        }else if ("webImage".equals(type)){
            dir = "web/image";
        }else if ("teacherImage".equals(type)){
            dir = "approve/image";
        }
        ResultBean resultBean=null;
        OSSClient client = new OSSClient(endpoint, accessId, accessKey);
        try {
            long expireTime = 30;
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);

            String postPolicy = client.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = client.calculatePostSignature(postPolicy);

            Map<String, String> respMap = new LinkedHashMap<String, String>();
            respMap.put("accessid", accessId);
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            respMap.put("dir", dir);
            respMap.put("host", host);
            respMap.put("expire", String.valueOf(expireEndTime / 1000));
            // respMap.put("expire", formatISO8601Date(expiration));

            JSONObject jasonCallback = new JSONObject();
            //jasonCallback.put("callbackUrl", callbackUrl);
            jasonCallback.put("callbackBody",
                    "filename=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}");
            jasonCallback.put("callbackBodyType", "application/x-www-form-urlencoded");
            String base64CallbackBody = BinaryUtil.toBase64String(jasonCallback.toString().getBytes());
            respMap.put("callback", base64CallbackBody);

            JSONObject ja1 = JSONObject.fromObject(respMap);
            // System.out.println(ja1.toString());
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "GET, POST");
            resultBean = new SuccessResultBean(ja1);
            this.setAjaxResponseResult(response,resultBean);

        } catch (Exception e) {
            // Assert.fail(e.getMessage());
            System.out.println(e.getMessage());
        }
    }
}
